//
//  HandWritingView.m
//  etionUI
//
//  Created by wangjian on 12/9/13.
//  Copyright (c) 2013 GuangZhouXuanWu. All rights reserved.
//

#import "HandWritingView.h"
#import "HandWritingInputView.h"
#import "CircleButton.h"
#import "ExtendSelector.h"
#import "UserGuideView.h"
#import "UserGuideManager.h"

#define BTN_SIZE 32
#define BTN_BORDER_DISTANCE 15
#define BTN_MARGIN 10
#define MARGIN 10

@interface CHandWritingView() <CHandWritingInputViewDelegate>

@property (nonatomic, retain) CHandWritingInputView *inputView;
@property (nonatomic, retain) NSMutableArray *arWordsView;
@property (nonatomic, assign) CGPoint writeLoc;
@property (nonatomic, assign) CGPoint writeLocOffset;

@property (nonatomic, assign) CCircleButton *delBtn;
@property (nonatomic, assign) CCircleButton *saveBtn;
@property (nonatomic, assign) CCircleButton *cancelBtn;
@property (nonatomic, assign) CExtendItemSelector *modeSelector;

@property (nonatomic, assign) CGFloat wordZoomRate;

@end

@implementation CHandWritingView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        self.inputView = [[[CHandWritingInputView alloc] initWithFrame:CGRectMake(0, BTN_BORDER_DISTANCE+BTN_SIZE+5, self.width, self.height - BTN_BORDER_DISTANCE+BTN_SIZE+5)] autorelease];
        _inputView.delegate = self;
        [self addSubview:_inputView];
        
        self.arWordsView = [NSMutableArray array];
        
        self.cancelBtn = [[[CCircleButton alloc] initWithFrame:CGRectMake(-BTN_SIZE, BTN_BORDER_DISTANCE, BTN_SIZE, BTN_SIZE) normalImage:[UIImage imageNamed:@"pb_backarrow_normal"] highlightedImage:[UIImage imageNamed:@"pb_backarrow_selected"]] autorelease];
        [self.cancelBtn addTarget:self action:@selector(cancelEdit) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.cancelBtn];
        
        self.delBtn = [[[CCircleButton alloc] initWithFrame:CGRectMake(self.width, BTN_BORDER_DISTANCE, BTN_SIZE, BTN_SIZE) normalImage:[UIImage imageNamed:@"pb_backspace_normal"] highlightedImage:[UIImage imageNamed:@"pb_backspace_selected"]] autorelease];
        [self.delBtn addTarget:self action:@selector(delLastWord) forControlEvents:UIControlEventTouchUpInside];
        self.delBtn.alpha = 0.0;
        [self addSubview:self.delBtn];
        
        self.modeSelector = [[[CExtendItemSelector alloc] initWithFrame:CGRectMake(self.width+BTN_SIZE+BTN_MARGIN, BTN_BORDER_DISTANCE, BTN_SIZE, BTN_SIZE) normalImages:[NSArray arrayWithObjects:[UIImage imageNamed:@"pb_sign_normal"], [UIImage imageNamed:@"pb_signligature_normal"], nil] highlightedImages:[NSArray arrayWithObjects:[UIImage imageNamed:@"pb_sign_selected"], [UIImage imageNamed:@"pb_signligature_selected"], nil] titles:[NSArray arrayWithObjects:@"单字输入", @"连写输入", nil]] autorelease];
        self.modeSelector.extendDir = EExtendSelectorDirDown;
        [self.modeSelector addTarget:self action:@selector(inputModeChange:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:self.modeSelector];
        
        self.saveBtn = [[[CCircleButton alloc] initWithFrame:CGRectMake(self.width+2*(BTN_SIZE+BTN_MARGIN), BTN_BORDER_DISTANCE, BTN_SIZE, BTN_SIZE) normalImage:[UIImage imageNamed:@"pb_save_normal"] highlightedImage:[UIImage imageNamed:@"pb_save_selected"]] autorelease];
        [self.saveBtn addTarget:self action:@selector(saveEdit) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.saveBtn];
        
        self.displayFrame = self.bounds;
        self.contentSize = self.bounds.size;
        
        [self showButtonsAnimated:YES complete:^(BOOL finished) {
            if ([CUserGuideManager userGuideStatusForKey:@"HandWritingView"] == EUserGuideStatusNeverDisplay)
            {
                CUserGuideUnit *unitBack = [CUserGuideUnit unitWithType:EUserGuideUnitTypeCircleNode area:_cancelBtn.frame text:@"点击这里返回，取消您的涂鸦" image:nil];
                CUserGuideUnit *unitSave = [CUserGuideUnit unitWithType:EUserGuideUnitTypeCircleNode area:_modeSelector.frame text:@"点击这里可以切换输入模式，包括单字输入和连写输入" image:nil];
                CUserGuideUnit *unitText = [CUserGuideUnit unitWithType:EUserGuideUnitTypeText area:CGRectInset(self.bounds, 40, 100) text:@"在屏幕上书写您想要的文字，写完后等待一秒，程序会将您的文字缩放为合适的大小，放置在图片合适的位置。\n切换输入模式会清空之前的输入。\n连写模式只能输入一次。" image:nil];
                [[CUserGuideView userGuideViewWithUnits:[NSArray arrayWithObjects:unitBack, unitSave, unitText, nil] delegate:nil] show];
                [CUserGuideManager setUserGuideStatus:EUserGuideStatusHasDisplay forKey:@"HandWritingView"];
            }
        }];
    }
    return self;
}

- (void)dealloc
{
    [_inputView release];
    [_arWordsView release];
    [super dealloc];
}

- (void)setDisplayFrame:(CGRect)displayFrame
{
    _displayFrame = displayFrame;
    
    self.writeLocOffset = CGPointMake(MARGIN, CGRectGetMinY(displayFrame)<self.cancelBtn.bottom ? self.cancelBtn.bottom + MARGIN - CGRectGetMinY(displayFrame) : MARGIN);
    self.writeLoc = CGPointMake(CGRectGetMinX(displayFrame)+self.writeLocOffset.x, CGRectGetMinY(displayFrame)+self.writeLocOffset.y);
    self.wordZoomRate = _contentSize.width/_displayFrame.size.width;
}

- (void)setContentSize:(CGSize)contentSize
{
    _contentSize = contentSize;
    self.wordZoomRate = contentSize.width/_displayFrame.size.width;
}

- (CGSize)standardSize
{
    if (self.mode == EHandWritingViewModeSingleWord)
    {
        if (self.displayFrame.size.width < self.displayFrame.size.height)
        {
            return CGSizeMake(self.displayFrame.size.width/6, self.displayFrame.size.width/6);
        }
        else
        {
            return CGSizeMake(self.displayFrame.size.height/6, self.displayFrame.size.height/6);
        }
    }
    else
    {
        if (self.displayFrame.size.width < self.displayFrame.size.height)
        {
            return CGSizeMake(CGRectGetWidth(self.displayFrame)/2, CGRectGetHeight(self.displayFrame)/3);
        }
        else
        {
            return CGSizeMake(CGRectGetWidth(self.displayFrame)/3, CGRectGetHeight(self.displayFrame)/2);
        }
    }
}

- (void)showButtonsAnimated:(BOOL)animated complete:(void (^)(BOOL finished))complete
{
    [UIView animateWithDuration:animated?.25:0.0 animations:^{
        self.cancelBtn.left = BTN_BORDER_DISTANCE;
        self.saveBtn.right = self.width - BTN_BORDER_DISTANCE;
        self.modeSelector.right = self.saveBtn.left-BTN_MARGIN;
//        [self.modeSelector setDisplayOffset:CGPointMake(self.saveBtn.left-BTN_MARGIN-self.modeSelector.right, 0)];
        self.delBtn.right = self.modeSelector.left-BTN_MARGIN;
    } completion:^(BOOL finished) {
        complete(finished);
    }];
}

- (void)hideButtonsAnimated:(BOOL)animated complete:(void (^)(BOOL finished))complete
{
    [UIView animateWithDuration:animated?.25:0.0 animations:^{
        self.cancelBtn.right = 0;
        self.delBtn.left = self.width;
        self.modeSelector.left = self.delBtn.right+BTN_MARGIN;
//        [self.modeSelector setDisplayOffset:CGPointMake(self.delBtn.right+BTN_MARGIN-self.modeSelector.left, 0)];
        self.saveBtn.left = self.modeSelector.right+BTN_MARGIN;
    } completion:^(BOOL finished) {
        complete(finished);
    }];
}

- (void)delLastWord
{
    if (self.arWordsView.count == 0)
    {
        return;
    }
    
    [self.modeSelector shrink];
    
    UIView *lastWord = [self.arWordsView lastObject];
    [self.arWordsView removeLastObject];
//    CGFloat standardH = [self standardSize].height;
    self.writeLoc = CGPointMake(lastWord.left, lastWord.top);
    
    [UIView animateWithDuration:.25 animations:^{
        lastWord.transform = CGAffineTransformScale(CGAffineTransformIdentity, .5, .5);
        lastWord.alpha = 0.0;
    } completion:^(BOOL finished) {
        [lastWord removeFromSuperview];
    }];
    
    if (self.arWordsView.count == 0)
    {
        [UIView animateWithDuration:.25 animations:^{
            self.delBtn.alpha = 0.0;
        }];
    }
}

- (void)delAllWord
{
    if (self.arWordsView.count == 0)
    {
        return;
    }
    
    NSArray *arTmp = [self.arWordsView copy];
    [UIView animateWithDuration:.25 animations:^{
        for (UIView *wordView in arTmp)
        {
            wordView.transform = CGAffineTransformScale(CGAffineTransformIdentity, .5, .5);
            wordView.alpha = 0.0;
        }
        self.delBtn.alpha = 0.0;
    } completion:^(BOOL finished) {
        for (UIView *wordView in arTmp)
        {
            [wordView removeFromSuperview];
        }
        [arTmp release];
    }];
    
    [self.arWordsView removeAllObjects];
    self.writeLoc = CGPointMake(CGRectGetMinX(self.displayFrame)+self.writeLocOffset.x, CGRectGetMinY(self.displayFrame)+self.writeLocOffset.y);
}

- (void)cancelEdit
{
    [self.inputView cancelInput];
    [UIView animateWithDuration:.25 animations:^{
        for (UIView *view in self.arWordsView)
        {
            view.alpha = 0.0;
        }
    }];
    [self.delegate handWritingViewCancelEdit:self];
}

- (void)saveEdit
{
    [self.inputView cancelInput];
    CGFloat zoomRate = self.contentSize.width/self.displayFrame.size.width;
    UIGraphicsBeginImageContext(self.contentSize);
    for (UIImageView *wordView in self.arWordsView)
    {
        [wordView.image drawAtPoint:CGPointMake((wordView.left-self.displayFrame.origin.x)*zoomRate, (wordView.top-self.displayFrame.origin.y)*zoomRate)];
    }
    UIImage *contentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.delegate handWritingView:self finishEditWithContent:contentImage];
}

- (void)inputModeChange:(CExtendItemSelector *)selector
{
    if (self.mode != selector.curSelectedIndex)
    {
        [self delAllWord];
    }
    self.mode = (EHandWritingViewMode)selector.curSelectedIndex;
}

#pragma mark - hand writing deleagate

- (BOOL)handWritingInputViewShouldStartInput:(CHandWritingInputView *)view
{
    if (self.mode == EHandWritingViewModeMultiWord && self.arWordsView.count > 0)
    {
        return NO;
    }
    
    if (self.modeSelector.bIsExtend == YES)
    {
        [self.modeSelector shrink];
        return NO;
    }
    return YES;
}

- (void)handWritingInputView:(CHandWritingInputView *)view inputWord:(UIImage *)word inFrame:(CGRect)frame
{
    CGRect orgFrame = frame;
    CGRect desFrame;
    CGFloat wordDspW = frame.size.width, wordDspH = frame.size.height;
    CGSize standardSize = [self standardSize];
    
    UIImage *newWord = word;
    if (wordDspW > standardSize.width || wordDspH > standardSize.height)
    {
        [UIImage caleFitImageSize:word.size targetSize:standardSize width:&wordDspW height:&wordDspH];
    }
    UIGraphicsBeginImageContext(CGSizeMake(wordDspW*self.wordZoomRate, wordDspH*self.wordZoomRate));
    [word drawInRect:CGRectMake(0, 0, wordDspW*self.wordZoomRate, wordDspH*self.wordZoomRate)];
        newWord = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

    if (self.writeLoc.x+MARGIN+wordDspW > CGRectGetMaxX(self.displayFrame))
    {
        self.writeLoc = CGPointMake(CGRectGetMinX(self.displayFrame)+MARGIN, self.writeLoc.y + standardSize.height);
    }
    desFrame = CGRectMake(self.writeLoc.x, self.writeLoc.y+(standardSize.height-wordDspH)/2, wordDspW, wordDspH);
    if (self.mode == EHandWritingViewModeMultiWord)
    {
        desFrame.origin.y = self.writeLoc.y;
    }
    self.writeLoc = CGPointMake(self.writeLoc.x+wordDspW+MARGIN/2, self.writeLoc.y);
    
    UIImageView *wordView = [[[UIImageView alloc] initWithImage:newWord] autorelease];
    wordView.frame = orgFrame;
    [self addSubview:wordView];
    [UIView animateWithDuration:.3 animations:^{
        wordView.frame = desFrame;
    } completion:^(BOOL finished) {
        
    }];
    [self.arWordsView addObject:wordView];
    
    if (self.arWordsView.count == 1)
    {
        [UIView animateWithDuration:.3 animations:^{
            self.delBtn.alpha = 1.0;
        }];
        if ([CUserGuideManager userGuideStatusForKey:@"HandWritingViewDel"] == EUserGuideStatusNeverDisplay)
        {
            CUserGuideUnit *unitDel = [CUserGuideUnit unitWithType:EUserGuideUnitTypeCircleNode area:_delBtn.frame text:@"点击这里可删除先前的输入" image:nil];
            [[CUserGuideView userGuideViewWithUnits:[NSArray arrayWithObjects:unitDel, nil] delegate:nil] show];
            [CUserGuideManager setUserGuideStatus:EUserGuideStatusHasDisplay forKey:@"HandWritingViewDel"];
        }
    }
}

- (UIImage *)handWritingImage
{
    if (self.arWordsView.count == 0)
    {
        return nil;
    }
    CGRect frame = [[self.arWordsView objectAtIndex:0] frame];
    for (UIView *wordView in self.arWordsView)
    {
        frame = CGRectUnion(frame, wordView.frame);
    }
    
    UIGraphicsBeginImageContext(frame.size);
    for (UIImageView *wordView in self.arWordsView)
    {
        [wordView.image drawInRect:CGRectMake(wordView.left-MARGIN, wordView.top-MARGIN, wordView.width, wordView.height)];
    }
    UIImage *handWritingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return handWritingImage;
}

@end
